package idiolect.helpers;

import idiolect.core.Word;

import java.util.*;

public class CompositeTranscriptionHelper extends AbstractHelper implements ResponseAcceptor {

    Map<String, String> responses = new HashMap<String, String>();
    private String[] words;

    public CompositeTranscriptionHelper(String request, ResponseAcceptor requestor, int taskID) {
        super(request, requestor, taskID);
        Set<String> set = new LinkedHashSet<String>(Arrays.asList(request.split("\\W+")));
        set.remove("");
        set.remove(null);
        words = set.toArray(new String[set.size()]);
    }

    public void run() {
        for (String word : words) {
            new MultitranTranscriptionHelper(word, this, taskID).doRequest();
        }
        try {
            synchronized (request) {
                request.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    public void setResponse(AbstractHelper source, String response) {
        if (source instanceof MultitranTranscriptionHelper) {
            if (response == null) {
                new LingvoTranscriptionHelper(source.getRequest(), this, taskID).doRequest();
                return;
            } else {
                responses.put(source.getRequest(), response);
            }
        }
        if (source instanceof LingvoTranscriptionHelper) {
            responses.put(source.getRequest(), response);
        }
        if (responses.size() == words.length) {
            StringBuilder sb = new StringBuilder();
            for (String word : words) {
                String str = responses.get(word);
                if (str == null && words.length == 1)
                    continue;
                sb.append(str != null ? str : Word.EMPTY_TRANSCRIPTION).append(' ');
            }
            this.response = sb.toString().trim();
            synchronized (request) {
                request.notify();
            }
        }
    }
}
